<?php
class AppController extends Controller {

    public $components = array('Auth', 'Acl', 'Cookie', 'Response', 'Eventful.Event');
    public $helpers = array('Html', 'Form', 'Javascript', 'Text', 'Time', 'Cache');
    public $paginate = array('limit'=>10);
    public $uses = array('User', 'Group', 'Option');
    protected $options = array();
    protected $searchable = array();
    protected $_blacklist = array('page', 'sort', 'direction');
    protected $_searchable = array(
        'like' => array('name', 'title', 'content', 'introduction', 'requirement', 'workplace', 'number'),
        'date' => array('created', 'modified')
    );
    /* Protected Variable to store current session user data */
    protected $user = array();
    protected $default_user = array(
        'id' => null,
        'type' => null,
        'name' => null,
        'group' => null
    );

    public function beforeFilter(){
        $this->Response->html();
        $this->_setAuth();
        $this->_setUser();
        $this->_setOptions();
        $this->_setLanguage();
        //$this->_saveUserAgent();
    }

    /* Set auth configurations */
    protected function _setAuth(){
        $this->Auth->authError = __('Sorry, session expired or you cannot access that page', true);
        $this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'dashboard');
        $this->Auth->logoutRedirect  = array('controller' => 'users', 'action' => 'home');
        $this->Auth->authorize = 'actions';
        $this->Auth->allow('viewByTag', 'cloud');
        $this->Auth->userScope = array('User.active' => '1');

        $this->Auth->autoRedirect = false;
        $this->Cookie->name = 'SME';

        if(!$this->Auth->user('id')){
            $cookie = $this->Cookie->read('User');
            if($cookie){
                $this->Auth->login($cookie);
            }
        }
    }

    /* Retrieve current session user data */
    protected function _setUser(){
        $this->user = $this->Session->read('Auth.User');
        if(!empty($this->user['id'])){
            $group = $this->Group->read(null, $this->user['group_id']);
            $this->user['name'] = $this->user['username'];
            $this->user['group'] = $group['Group']['name'];
            if($this->user['group'] == 'student'){
                $this->loadModel('Student');
                $student = $this->Student->findByNumber($this->user['name']);
                if(!empty($student['Student'])){
                    $this->user['name'] = $student['Student']['name'];
                    $this->user['student'] = $student['Student'];
                }
            }
        }else{
            $this->user = $this->default_user;
        }
        $this->set('user', $this->user);
    }

    /* Retrieve language preferences */
    protected function _setLanguage(){
        if($this->Cookie->read('lang') && !$this->Session->check('Config.language')){
            $this->Session->write('Config.language', $this->Cookie->read('lang'));
        }else if(isset($this->params['language']) && ($this->params['language']
                 !=  $this->Session->read('Config.language'))){

            $this->Session->write('Config.language', $this->params['language']);
            $this->Cookie->write('lang', $this->params['language'], null, '20 days');
        }else{
            /* to avoid error when sessiond deleted by client, set to the dafault */
            //$this->Session->write('Config.language', Configure::read('Config.language'));
        }
    }

    /* Begin to import application wide Configurations */
    protected function _setOptions(){
        $this->options = array(
            'queryDateFormat' => 'Y-m-d',
            'searchDateFormat' => 'Y-m-d H:i:s',
        );
        $options = $this->Option->read(null, 1);
        $this->options = array_merge($this->options, $options['Option']);
        $this->set('options', $this->options);
    }

    /* Save user agent information, which will be removed in the near future */
    protected function _saveUserAgent(){
        $this->loadModel('UserAgent');
        $data['UserAgent'] = get_browser(null, true);
        if(isset($data['UserAgent']['platform']) && !empty($data['UserAgent']['platform'])){
            $this->UserAgent->save($data);
        }
    }

    /* Set CKFinderPath used in posts and companies */
    protected function _setCKFinderPath(){
        $this->set('CKFinderPath', Configure::read('CKFinder.url'));
    }

    /**
     * Method accord with ModelBehavior.Switchable, mainly on post, jobs
     */
    public function switchOn($field=null, $id=null){
        $data = compact('field', 'id');
        if($this->{$this->modelClass}->switchOn($field, $id)){
            $this->Response->json(true, __('Changes have been saved', true), $data);
        }else{
            $this->Response->json(false, __('Changes failed to save', true), $data);
        }
    }
    public function switchOff($field=null, $id=null){
        $data = compact('field', 'id');
        if($this->{$this->modelClass}->switchOff($field, $id)){
            $this->Response->json(true, __('Changes have been saved', true), $data);
        }else{
            $this->Response->json(false, __('Changes failed to save', true), $data);
        }
    }

    /**
     * justify Paginator Search onditions
     * some fields need special handling, Comment.content, Post.title, Post.content
     */
    protected function _justifyPaginator(){
        /* set paginate limit anyway */
        $this->paginate['limit'] = $this->options['indexPageLimit'];
        if(empty($this->params['named'])){ return; }
        $options = array_merge($this->searchable, $this->params['named']);
        $model = $this->modelClass;
        $blacklist = $this->_blacklist;
        $this->paginate['conditions'] = array();
        foreach($options as $field=>$condition){
            if(!in_array($field, $blacklist) && !empty($condition)){
                $this->paginate['conditions'][$model.'.'.$field] = $condition;
            }
        }
        $this->_justifyLikeFields($options, $model);
        $this->_justifyDateFields($options, $model);
    }

    /* justify LIKE searching fields, title, content, requirement, etc */
    protected function _justifyLikeFields($options, $model){
        $likes = $this->_searchable['like'];
        foreach($likes as $i=>$like){
            if(!empty($options[$like])){
                unset($this->paginate['conditions'][$model.'.'.$like]);
                $this->paginate['conditions'][$model.'.'.$like.' LIKE '] = '%'.$options[$like].'%';
            }
        }
    }

    /* justify DATETIME searching fields, created, modified, etc */
    protected function _justifyDateFields($options, $model){
        $dates = $this->_searchable['date'];
        $format = $this->options['searchDateFormat'];
        foreach($dates as $i=>$date){
            if(!empty($options[$date])){
                unset($this->paginate['conditions'][$model. '.' .$date]);
                $time = strtotime($options[$date] . '+1day');
                $today = date($format, strtotime($options[$date]));
                $tomorrow = date($format, $time);
                $this->paginate['conditions'][$model. '.' .$date.' BETWEEN ? AND ?'] = array($today, $tomorrow);
            }
        }
    }

    /* Delete method shared by all subclasses, which is the same logic in every SubController */
    public function delete($id = null){
        $model = $this->modelClass;
        if(!empty($this->params['named'])){}
        if(!$id){
            $this->Response->json(false, __('Invalid id for delete operation', true));
        }else{
            if($this->{$model}->del($id)){
                $this->Response->json(true, __('Item deleted', true));
            }else{
                $this->Response->json(false, __('Item not deleted', true));
            }
        }
    }

    public function viewByTag($slug=null){
        $this->helpers[] = 'Taggable';
        $model = $this->modelClass;
        $this->set($this->{$model}->viewByTag($slug));
        $this->render('/elements/view_by_tag');
    }

}
?>